package kmitl.comsci.bustacker;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class SelectLineActivity extends Activity {
	
	final static int REQ_CODE = 1;
	Typeface fontFace;
	private String start_name ;
	private String end_name;
	String[] str ;
	private String start_loc_id;
	private String start_loc_latitude;
	private String start_loc_longitude;
	
	
	private HttpPost httppost;
    private HttpClient httpclient;
    private List<NameValuePair> nameValuePairs;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.selectline);
		
		//--recieve data before page
		Bundle bundle = this.getIntent().getExtras();
		
		if(bundle != null){
			start_name 	 = bundle.getString("start_name");
			end_name = bundle.getString("end_name");
								
		 }
		
		JSONObject jObject = initTextList();
		
		List<String> arrList = new ArrayList<String>();
		
		try {
					
			arrList = getDataFromJson(jObject);
			
		} catch (Exception e) {
			
			e.printStackTrace();
		}
				
		
		str = getBusLine(arrList.get(0));
						
		start_loc_latitude  = arrList.get(1);
		start_loc_longitude = arrList.get(2);
		start_loc_id 		 = arrList.get(3);
		
		//--set font
		 
		fontFace = Typeface.createFromAsset(getAssets(),"fonts/THSarabunNew.ttf");
		
		
		ListView listView = (ListView) findViewById(R.id.selectline_listView);
		listView.setAdapter(new ArrayAdapter<Object>(this, android.R.layout.simple_list_item_1, str));
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				Intent intent = new Intent(SelectLineActivity.this, ShowLineActivity.class);
				
				//---- send data to next page
			    Bundle bundle = new Bundle();
			    bundle.putString("origin_loc_latitude",start_loc_latitude);
			    bundle.putString("origin_loc_longitude", start_loc_longitude);
			    bundle.putString("origin_loc_id", start_loc_id);
			    bundle.putString("bus_route_id",  String.valueOf(arg0.getItemAtPosition(arg2)));
			    
			    intent.putExtras(bundle);
			    //startActivity(intent);
			    startActivityForResult(intent, REQ_CODE);
				finish();
			}
		});
		
		Button backBT = (Button)findViewById(R.id.backButton);
		backBT.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				Intent intent = new Intent(SelectLineActivity.this, SearchActivity.class);
				startActivity(intent);
				finish();
			}
		});
		
	}
	
	public void connectServer() {
		
	}
	
	private JSONObject initTextList() {
		//--StrictMode
		StrictMode.ThreadPolicy policy = new
				StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
				StrictMode.setThreadPolicy(policy);
	    
		//---connect to server	
		httpclient 		= new DefaultHttpClient();
		httppost 		= new HttpPost("http://161.246.13.242/itone/php_get_bus_route.php");
		nameValuePairs  = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("origin",start_name ));
		nameValuePairs.add(new BasicNameValuePair("destination" ,end_name));
		
		//-------------------------------------------------------------
		InputStream is = null;
        String result = null;
        JSONObject jsObj = null;
       
        try {
            
            httppost.setEntity((HttpEntity) new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
 
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
 
            is.close();
            result = sb.toString();
            
        
        } catch (ClientProtocolException e) {
            Log.e("ConnectServer", e.toString());
        } catch (IOException e) {
            Log.e("ConnectServer", e.toString());
        }
        try {
			jsObj =  new JSONObject(result);
		} catch (JSONException e) {
			
			e.printStackTrace();
		}
		
        return jsObj;
	}
	public ArrayList<String> getDataFromJson(JSONObject jsonObject)throws IllegalStateException,IOException, JSONException, NoSuchAlgorithmException 
	{
		ArrayList<String> busRoute = new ArrayList<String>();
		JSONArray array = jsonObject.getJSONArray("Bus Route");		 
		 	 
		
		if(array!=null)
	    {	 
			 for(int i = 0; i<array.length(); i++) 
			 {
					busRoute.add(array.getJSONObject(i).getString("bus_route_id"));
					busRoute.add(array.getJSONObject(i).getString("bus_route_start_latitude"));
					busRoute.add(array.getJSONObject(i).getString("bus_route_start_longitude"));
					busRoute.add(array.getJSONObject(i).getString("bus_route_start_id"));
			 }
			 	
	      }
		
		return busRoute;
				
	}
	public String[] getBusLine(String s) {
		
		int start = 0;
		int count = 0;
		
		while(s.indexOf("," ,start)!=-1) {
			start = s.indexOf("," ,start)+1;
			count++;
		}
			
		start = 0;
		String[] strBL = new String[count+1];
		
		for(int i=0;i<count;i++) {
			strBL[i] = s.substring(start ,s.indexOf("," ,start));
			start = s.indexOf("," ,start)+1;
		}
		strBL[count] = s.substring(start,s.length());
		
				
		return strBL;
	}
}
